86. Partition List
86. Partition List
题目
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
解析
- 思路:新建两个节点preHead1与preHead2,分别为指向两个链表的头结点。把节点值小于x的节点链接到链表1上,节点值大等于x的节点链接到链表2上。最后把两个链表相连即可
- right.next=null;//这句很重要!链表最后一个元素如果小于x的话,那么right.next不为null; 自己的没有想到,画个简单的示意图就知道,为甚末要置NULL,后面就绕开了这个问题,分离每一个节点
// 86. Partition List
class Solution_86 {
public:
ListNode* partition(ListNode* head, int x) {
if (!head||!head->next)
{
return head;
}
ListNode*cur = head;
ListNode*left = new ListNode(0);
ListNode*p = left;
ListNode*right = new ListNode(0);
ListNode*q = right;
while (cur)
{
ListNode* temp = cur;
cur = cur->next;
temp->next = NULL;
if (temp->val<x)
{
left->next = temp;
left = left->next;
}
else
{
right->next = temp;
right = right->next;
}
}
left->next = q->next;
return p->next;
}
};
题目来源
C/C++基本语法学习
STL
C++ primer